package org.light.facade;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.javaforever.poitranslator.core.ProjectExcelWorkBook;
import org.light.domain.Project;
import org.light.domain.ValidateInfo;
import org.light.exception.ValidateException;
import org.light.shiroauth.ShiroAuthModule;
import org.light.simpleauth.SimpleAuthModule;
import org.light.utils.ProjectDecorateUtil;
import org.light.wizard.ExcelWizard;

import com.hmkcode.MultipartRequestHandler;
import com.hmkcode.vo.TransformerFileMeta;

import net.sf.json.JSONObject;

/**
 * 
 * @author Jerry Shen 2024-9-23
 *
 */
public class Sgs2ExcelTransformerFacade extends HttpServlet {
	private static final long serialVersionUID = 147513641619203107L;
	
	//private List<TransformerFileMeta> files = new LinkedList<TransformerFileMeta>();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Sgs2ExcelTransformerFacade() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}	

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Map<String, Object> result = new TreeMap<String, Object>();
		try {
			// 1. Upload File Using Apache FileUpload
			List<TransformerFileMeta> files = new ArrayList<TransformerFileMeta>();
			files.addAll(MultipartRequestHandler.transformerUploadByApacheFileUpload(request));

			String excelfolder = request.getSession().getServletContext().getRealPath("/") + "spreadsheets/";
			excelfolder = excelfolder.replace('\\', '/');
			System.out.println("JerryDebug:excelfolder:"+excelfolder);
			
			String language = files.get(0).getLanguage().toLowerCase();
			String technicalstack = files.get(0).getTechnicalstack().toLowerCase();
						
			String [] fileNames =  files.get(0).getFileName().replace('\\', '/').split("/");
			String fileName = "";
			if (fileNames.length > 0) fileName = fileNames[fileNames.length-1];
			else throw new ValidateException("文件上传出错");

			byte [] bytes = files.get(0).getContent().readAllBytes();
			
			try (ByteArrayInputStream is2 = new ByteArrayInputStream(bytes)){
				HSSFWorkbook wb = new HSSFWorkbook(is2);
	
				ProjectExcelWorkBook pewb = new ProjectExcelWorkBook();
			
				Project project = pewb.pureTranslate(wb,true,true,true);
				String root = request.getSession().getServletContext().getRealPath("/").replace('\\', '/');
				String genExcelFile = project.getStandardName() + ".xls";
	
				if ("golang".equals(language)) {
					project = ProjectDecorateUtil.decorateJavaProjectToSimple(project);
					project.setComputerLanguage("go");
					project.setTechnicalstack(technicalstack);
				}else if ("rust".equals(language)) {
					project = ProjectDecorateUtil.decorateJavaProjectToTower(project);
					project.setComputerLanguage(language);
					project.setTechnicalstack(technicalstack);
				}else if ("java".equals(language)&&("smeu".equals(technicalstack)||"msmeu".equals(technicalstack)||"sbmeu".equals(technicalstack))) {
					if (project.getModules()!=null&&project.getModules().size()>0) {
						SimpleAuthModule sam = (SimpleAuthModule) project.getModules().get(0);
						sam.setStandardName("ShiroAuth");
					}	
					project.setComputerLanguage(language);
					project.setTechnicalstack(technicalstack);
				}
				ExcelWizard.outputExcelWorkBook(project, (root+ "source/").replace("\\", "/"),genExcelFile);
				
				result.put("success", true);
				result.put("projectName",project.getStandardName());
				out.print(JSONObject.fromObject(result));
			}
		} catch (ValidateException ev) {
			result.put("success", false);
			ValidateInfo info = ev.getValidateInfo();
			List<String> compileErrors = info.getCompileErrors();
			result.put("compileErrors", compileErrors);
			List<String> compileWarnings = info.getCompileWarnings();
			result.put("compileWarnings", compileWarnings);
			out.print(JSONObject.fromObject(result));
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof ValidateException) {
				ValidateException ev = (ValidateException)e;
				result.put("success", false);
				ValidateInfo info = ev.getValidateInfo();
				List<String> compileErrors = info.getCompileErrors();
				result.put("compileErrors", compileErrors);
				List<String> compileWarnings = info.getCompileWarnings();
				result.put("compileWarnings", compileWarnings);
				out.print(JSONObject.fromObject(result));
				return;
			}
			if (!(e instanceof ValidateException)) {
				e.printStackTrace();
				result.put("success", false);
				if (e.getMessage() != null && !e.getMessage().equals("")) {
					result.put("compileErrors", new ArrayList<String>().add(e.getMessage()));
				} else {
					result.put("compileErrors", new ArrayList<String>().add("空指针或其他语法错误！"));
				}
				out.print(JSONObject.fromObject(result));
			}
		} 
	}
}
